package krasa.mavenhelper.file;

import java.io.*;

/**
 * @Author
 * @Date 2024/1/31 11:06
 * @Version 1.0
 */
public class FileHolder {
    private static final String filePath = "C:\\Datas\\maven\\mavenHelper\\test.txt";
    private static final File file = new File(filePath);

    public static File getFile() {
        return file;
    }

    public static File write(String s,File file) {
        FileHolder fileWriter = new FileHolder();
        return fileWriter.write(s+"\n", true,file);
    }
    public static File write(String s) {
        return write(s, file);
    }

    /**
     * 将String写入文件
     *
     * @param content  写入的内容
     * @param isAppend 是否追加
     * @return 目标文件
     */
    public File write(String content, boolean isAppend,File file) {
        BufferedWriter writer = null;
        try {
            writer = getWriter(isAppend,file);
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return file;
    }

    public BufferedWriter getWriter(boolean isAppend,File file) {
        try {
            return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(touch(file), isAppend)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static File touch(File file) {
        if (null == file) {
            return null;
        }
        if (false == file.exists()) {
            mkParentDirs(file);
            try {
                //noinspection ResultOfMethodCallIgnored
                file.createNewFile();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return file;
    }


    /**
     * 创建文件夹，会递归自动创建其不存在的父文件夹，如果存在直接返回此文件夹<br>
     * 此方法不对File对象类型做判断，如果File不存在，无法判断其类型
     *
     * @param dir 目录
     * @return 创建的目录
     */
    public static File mkdir(File dir) {
        if (dir == null) {
            return null;
        }
        if (false == dir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 创建所给文件或目录的父目录
     *
     * @param file 文件或目录
     * @return 父目录
     */
    public static File mkParentDirs(File file) {
        if (null == file) {
            return null;
        }
        return mkdir(file.getParentFile());
    }
}
